package org.singledog.form.builder.storage;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 前期先从文件系统里面读取  后期再迁移到DB里面
 */
@Slf4j
public class FileSchemaReader {

    private static final Map<String, String> storageCache = new ConcurrentHashMap<>();

    public static String getSchema(String classpath) {
        String schema = storageCache.get(classpath);
        if (!StringUtils.isEmpty(schema)) {
            return schema;
        }

        schema = readSchemaFromFile(classpath);
        if (!StringUtils.isEmpty(schema)) {
            storageCache.put(classpath, schema);
        }

        return schema;
    }

    public static String readSchemaFromFile(String classpath) {
        Resource resource = new ClassPathResource(classpath);
        if (resource.exists() && resource.isReadable()) {
            try (InputStream is = resource.getInputStream()) {
                return IOUtils.toString(is, "UTF-8");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        } else {
            log.error("path {} not exists or can't read !", classpath);
        }

        return null;
    }

    public static void clearCache() {
        storageCache.clear();
    }

}
